package com.hzit.hzb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.hzit.common.exception.BusinessException;
import com.hzit.common.result.R;
import com.hzit.common.result.ResponseEnum;
import com.hzit.hzb.core.pojo.dto.ExcelDictDTO;
import com.hzit.hzb.core.pojo.entity.Dict;
import com.hzit.hzb.core.service.DictService;
import com.hzit.hzb.core.service.FileService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author hbxfwf
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/admin/core/dict")
@Api(tags = "字典管理接口")
public class AdminDictController {

	@Autowired
	private DictService dictService;

	@ApiOperation("读取上传的Excel文件并写到数据库中")
	@PostMapping("/import")
	public R importData(
			@ApiParam(value = "上传的Excel文件",required = true)
			@RequestParam("file") MultipartFile file) throws IOException {
		InputStream inputStream = file.getInputStream();
		dictService.importData(inputStream);
		return R.ok().message("加载数据成功!");
	}

	@ApiOperation("将数据库中的数据导出到excel中")
	@GetMapping("/export")
	public void export(HttpServletResponse response){
		try {
			// 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("我的字典", "UTF-8").replaceAll("\\+", "%20");
			// 设置此请求头浏览器才会下载
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
		} catch (IOException e) {
			//EXPORT_DATA_ERROR(104, "数据导出失败"),
			throw  new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
		}
	}

	@ApiOperation("根据父id查询其下的字典列表")
	@GetMapping("/findByPid/{pid}")
	public R findByPid(@PathVariable("pid") @ApiParam("父id") Integer pid, HttpServletRequest request){
		List<Dict> dictList = dictService.findByPid(pid);
		// XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		// String username = xxlUser.getUsername();
		return R.ok().data("list",dictList);//.data("username",username);
	}

}

